var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();

Page({
  data: {
    util: util,
    orgInfo: '',
    org_name: '',
    bottom_nav_data: [],
    isIphone_x: false,
    screen_h: 0,
    screen_w: 0,

    scrollView_h: 480,

    showDatas: [],

    showVideo: false,
    roomDatas:[],

    selTitleIndex: '1',

    hasServiceUser: true,

    noServiceStr: "附近暂未有商户服务"
  },

  shopList: '',
  allUserList: '',


  cuid: '',
  userSex: '',
  token: '',
  openid: '',

  lat: 0,
  lon: 0,

  onLoad: function (data) {
    console.log("screen_w = " + app.screen_w)
    this.setData({
      isIphone_x: app.isIphone_x,
      screen_w: app.screen_w,
      screen_h: app.screen_h,
      scrollView_h: app.isIphone_x ? (app.screen_h - 70) : (app.screen_h - 50)
    });

    var that = this
    app.LoginUserInfo(function(res){
      console.log("登录用户信息：", res);
      if(res && res != '-1' && res != '-2'){
        that.cuid = res.uid
        that.userSex = res.sex
        that.token = res.token
        that.openid = res.openid
      }
    })
    this.initIndexView(data);
    app.getLocation(function(res){
      if (res.latitude && res.longitude) {
        that.lat = res.latitude
        that.lon = res.longitude
      }
      that.loadData()
    })
  },

  selectTitleItem: function (params) {
    let selIndex = params.currentTarget.dataset.index
    this.setData({
      selTitleIndex: selIndex
    })
    if (selIndex == '1') {
      if (this.shopList && this.shopList.length > 0) {
        this.setData({
          hasServiceUser: true,
          showDatas: this.shopList,
          noServiceStr: "附近暂未有商户服务"
        })
      } else {
        this.setData({
          hasServiceUser: true,
          showDatas: '',
          noServiceStr: "附近暂未有商户服务"
        })
        this.loadGHS()
      }
    } else {
      if (this.allUserList && this.allUserList.length > 0) {
        this.setData({
          hasServiceUser: true,
          showDatas: this.allUserList,
          noServiceStr: "附近暂未有师傅服务"
        })
      } else {
        this.setData({
          hasServiceUser: true,
          showDatas: '',
          noServiceStr: "附近暂未有师傅服务"
        })
        this.getAppUserList()
      }
    }
  },

  initIndexView: function (data) {
    var that = this;
    //初始化底部导航
    app.getBottomNavData('liaota/liaota', function (nav_data) {
      that.setData({
        bottom_nav_data: nav_data,
        nav_bgColor: nav_data[0].bgcolor
      });
    });
  },

  loadData: function() {
    var that =this
    app.getWxCheck(function(show) {
      that.setData({
        showVideo: show
      })
      if(show) {
        that.loadGHS()
      } else {
        that.getGoodsListData()
      }
    }, true)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  onShow: function () {
  },

    //供货商--用户门店类型的服务商
    loadGHS: function () {
      // http://admin.jawanology.com/go.php?ac=getShopList&binduid=2233&lon=1&lat=1&publickey=ZGZvI1mi8Q
      var that = this;
      var params = {
        publickey: util.publiccode,
        ac: "getShopList",
        lat: that.lat,
        lon: that.lon,
        // page: 1,
        // num: 300
      }
      util.api_go({
        data: params,
        success: function (responseData) {
          console.log("供货商数据：", responseData);
          var datas = responseData.data;
          if (!datas.msg) {
            datas.forEach(function (m) {
              let distanceInt = app.getDistance(that.lat, that.lon, m.lat, m.lon)
              m.distance = app.getDistanceStr(distanceInt)
            })
            that.shopList = datas
            that.setData({
              hasServiceUser: true,
              showDatas: datas
            })
          } else {
            that.setData({
              hasServiceUser: false
            })
          }
        
        }
      });
    },  

    //注册并显示在app上的用户，就是独立服务人员
    getAppUserList: function() {
    // String action = "getappuser&page=1&num=1000&sex=0&minage=" + minAge + "&maxage=" + maxAge;
    var that = this
    util.api_go({
        data: {
          "publickey": util.publiccode,
          "ac": "getxingxinguser",
          "lat": that.lat,
          "lon": that.lon,
          "page": 1,
          "num": 1000
        },
        success: function (responseData) {
          console.log("app用户列表：", responseData);
          // lat: "23.921038"
          // lon: "112.186094"
          if(!responseData.data.msg){
            var datas = responseData.data
            datas.forEach(function (m) {
              let distanceInt = app.getDistance(that.lat, that.lon, m.lat, m.lon)
              m.distance = app.getDistanceStr(distanceInt)
            })
            that.setData({
              hasServiceUser: true,
              showDatas: datas
            })
            that.allUserList = datas
          } else {
            that.setData({
              hasServiceUser: false
            })
          }
        }
      });
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    tt.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  goAtherPage: function (e) {
    console.log("goAtherPage!!!!!!!!");
    var url = e.currentTarget.dataset.link;
    tt.navigateTo({
      url: url
    })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    tt.redirectTo({
      url: url
    })
  },

  //底部导航跳转
  navigtionClick: function (e) {
    console.log("点击参数：", e);
    var path = e.currentTarget.dataset.path;
    console.log("跳转连接信息：", path);
    if (path) {
      if (path.indexOf('navto:') == 0) {
        var navPath = path.slice(6);
        tt.navigateTo({
          url: navPath,
        })
      } else {
        tt.redirectTo({
          url: path
        });
      }
    }
  },

  sendHelloMessage: function (e) {
    // post请求，ac=postmsg，传入uid-发送者uid，touid-接收者uid，msg-消息内容。返回操作成功/失败。调用成功后 会增加消息列表接口中的未读数量
    var toUid = e.currentTarget.dataset.uid
    var that = this;
    if (!that.cuid || that.cuid.length <= 0) {
      return
    }
    let noGetSubMsg = app.noSubscribeMessageCache()
    console.log("已经授权订阅消息：" + noGetSubMsg)
    if (noGetSubMsg) {
      tt.requestSubscribeMessage({
        tmplIds: [app.globalData.tmplMsgIds],
        success(res) {
          console.log("订阅消息结果：", res)
          if (res.errMsg.indexOf(":ok") > 0) {
            app.setSubscribeMessageCache()
          }
        }
      })
    }
    tt.navigateTo({
      url: '/pages/chatMessage/chatMessage?sayhello=true&uid=' + toUid
    })
  },

  makeCall: function (e) {
    
    let phoneNum = e.currentTarget.dataset.number
    console.log("makeCall", phoneNum)
    if (phoneNum && phoneNum.length > 2) {
      tt.makePhoneCall({
        phoneNumber: phoneNum,
        fail: function(res) {
          console.log("makeCall fail:", res)
        }
      })
    } else {
      tt.showToast({
        title: "电话号码为空"
      });
    }
  },


  //以下是审核内容
  getGoodsListData:function(){
    var that = this;
    this.setData({
      hasLoadding: true
    });
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      postuid: util.orgid,
      page: 1,
      num: 30
    };
    console.log("房间请求参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("房间数据：", responseData);
        that.setData({
          roomDatas: responseData.data
        })
        tt.hideLoading();
      }
    });
  },

})